<template>
	<view :class="class" :style="style" class="__lib-scroll-item" ref="scrollRef">
		<slot></slot>
	</view>
</template>

<script>
	/**
	 * @description 
	 * @property 
	 * @property 
	 */
	
	/** 是否正在移动 */
	let moveIng = false;
	export default {
		name: 'lib-scroll-item',
		emit: ['update:active', 'activeChange'],
		props: {
			type: {
				type: String,
				default: 'default',
				required: false,
			},
			class: {
				type: String,
				default: '',
				required: false,
			},
			style: {
				type: Object,
				default: () => {
					return {};
				},
				required: false,
			},
			active: {
				type: Number,
				default: -1,
				required: false,
			},
		},
		data() {
			return {
				/** 当前的page */
				activePage: 0,
				/** page总数 */
				totalPage: 0,
				
			}
		},
		methods: {
			prev() {
				if (this.activePage <= 0) {
					return;
				}
				this.activePage--;
				this.to(this.activePage);
			},
			next() {
				if (this.activePage >= this.totalPage - 1) {
					return;
				}
				this.activePage++;
				this.to(this.activePage);
			},
			/** 移动到 第index个 */
			to(index) {
				// 错误数据不处理
				if (index < 0 || index > this.totalPage) {
					return;
				}
				this.activePage = index;
				this.$emit('update:active', index);
				this.$emit('activeChange', index);
				// console.log(`activePage:${this.activePage}`);
				const scrollElement = this.$refs.scrollRef.$el;
				const childElements = scrollElement.children;
				const activeElement = childElements[this.activePage];
				if (activeElement) {
					activeElement.scrollIntoView({
						behavior: 'smooth', // 平滑滚动
						block: 'start', // 将子元素滚动到父元素的中心
						inline: 'start' // 水平方向对齐方式
					});
				}
				moveIng = true;
				
				setTimeout(()=>{
					moveIng = false;
				}, 500);
			},
			render() {
				const scrollElement = this.$refs.scrollRef.$el;
				const childElements = scrollElement.children;
				this.totalPage = childElements.length;
				scrollElement.addEventListener('wheel', (event) => {
					event.stopPropagation();
					event.preventDefault();
					/** 阻止连续滚动 */
					if(moveIng === true){
						return;
					}
					if (event.deltaY > 0) {
						this.next();
					} else if (event.deltaY < 0) {
						this.prev();
					} else {}
				}, false);
			},
		},
		mounted() {
			this.render();
			this.$watch('active', function(newValue, oldValue) {
				// console.log('active已变化：', oldValue, '->', newValue);
				if (+newValue >= 0) {
					this.to(+newValue);
				}
			}, {
				immediate: true
			});
		},
		updated() {

		},
		unmounted() {},
		destroyed() {},
		watch: {},
	}
</script>


<style lang="scss">
	@import "./lib-scroll-item.scss";
</style>